import sys
import threading
import time
import json
from msgdata import MsgData
from business import http_req
from netclinet import send_msg, client_init
import wx


class MyFrame1(wx.Frame):
    client = None
    subThread = None
    subThread_2 = None
    sleep_time = 30

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition,
                          size=wx.Size(800, 500), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)

        self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)

        bSizer1 = wx.BoxSizer(wx.VERTICAL)

        bSizer2 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer2.SetMinSize(wx.Size(790, 100))
        self.m_ip = wx.TextCtrl(self, wx.ID_ANY, u"请填写工号", wx.DefaultPosition, wx.Size(200, 50), 0)
        self.m_ip.SetFont(wx.Font(15, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, "宋体"))

        self.m_address = wx.TextCtrl(self, wx.ID_ANY, u"请填写ip地址", wx.DefaultPosition, wx.Size(200, 50), 0)
        self.m_address.SetFont(wx.Font(15, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, "宋体"))

        self.m_address_port = wx.TextCtrl(self, wx.ID_ANY, u"端口号", wx.DefaultPosition, wx.Size(100, 50), 0)
        self.m_address_port.SetFont(wx.Font(15, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, "宋体"))

        bSizer2.Add(self.m_ip, 0, wx.ALL, 5)
        bSizer2.Add(self.m_address, 0, wx.ALL, 5)
        bSizer2.Add(self.m_address_port, 0, wx.ALL, 5)

        self.m_btn = wx.Button(self, wx.ID_ANY, u"确定", wx.DefaultPosition, wx.Size(100, 50), 0)
        bSizer2.Add(self.m_btn, 0, wx.ALL, 5)

        bSizer1.Add(bSizer2, 1, wx.EXPAND, 5)

        self.m_content = wx.TextCtrl(self, wx.ID_ANY, u"", wx.DefaultPosition, wx.Size(790, 410),
                                     0 | wx.VSCROLL | wx.TE_MULTILINE | wx.TE_READONLY)

        self.m_content.SetFont(
            wx.Font(14, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, "宋体"))

        bSizer1.Add(self.m_content, 0, wx.ALL, 5)

        self.SetSizer(bSizer1)
        self.Layout()

        self.Centre(wx.BOTH)

        # Connect Events
        self.m_btn.Bind(wx.EVT_BUTTON, self.submit_click)
        #  启动心跳线程
        self.heart_task();

    def __del__(self):
        pass

    def heart_task(self):
        self.subThread_2 = threading.Timer(self.sleep_time, self.heart_message)
        self.subThread_2.start()

    # Virtual event handlers, overide them in your derived class
    def submit_click(self, event):
        work_code = self.m_ip.GetValue()
        address = self.m_address.GetValue()
        address_port = self.m_address_port.GetValue()
        self.m_btn.Disable()
        self.subThread =threading.Thread(target=self.netty_con,args=(work_code,address,address_port))
        self.subThread.start()

    def heart_message(self):
        if self.client is None:
            self.m_content.AppendText("no init" + "\r\n")
        elif self.m_ip.GetValue() is None:
            self.m_content.AppendText("no workcode" + "\r\n")
        else:
            msg = MsgData()
            msg._type = 'join'
            msg._sendId = self.m_ip.GetValue()
            msg._receiptId = self.m_ip.GetValue()
            print(msg.__dict__)
            # 将对象book转成JSON格式的数据
            # 将JSON格式数据转成字节类型,用于网络传输
            send_msg(json.dumps(dict(msg.__dict__)), self.client)
        # 继续定时任务
        self.heart_task()


    def netty_con(self,work_code,address,address_port):
        try:
            self.client = client_init(work_code,address,address_port)
        except Exception as e:
            init_Finish = False
            while not init_Finish:
                try:
                    self.client = client_init(work_code,address,address_port)
                except Exception as e2:
                    print("重新进行连接")
                    self.m_content.AppendText("重新进行连接" + "\r\n")
                    time.sleep(30)
                else:
                    init_Finish = True
        else:
            print("init is ok")
            self.m_content.AppendText("init is ok" + "\r\n")
        while True:
            try:
                ret = str(self.client.recv(1024), encoding="utf-8")
                receipt_data = json.loads(ret)
                print(receipt_data)
                obj = MsgData()
                obj.__dict__.update(receipt_data)
                if obj.type == 'join':
                    self.m_content.AppendText("join heart" + "\r\n")
                elif obj.type == 'quit':
                    self.m_content.AppendText("quit" + "\r\n")
                    sys.exit()
                elif obj.type == 'http':
                    self.m_content.AppendText("http request" + "\r\n")
                    res = http_req(obj)
                    obj.jsonMsg['result'] = res
                    send_msg(json.dumps(dict(obj.__dict__)), self.client)
                else:
                    print("no handler")
                    self.m_content.AppendText("no handler" + "\r\n")
                print("commond finished")
                self.m_content.AppendText("commond finished" + "\r\n")
                if self.m_content.GetNumberOfLines()>200:
                    self.m_content.Clear()
            except ConnectionResetError  as e:
                init_Finish = False
                while not init_Finish:
                    try:
                        print("再次重新进行连接")
                        self.m_content.AppendText("再次重新进行连接" + "\r\n")
                        self.client = client_init(work_code,address,address_port)
                    except Exception as e2:
                        print("再次重新进行连接")
                        self.m_content.AppendText("再次重新进行连接" + "\r\n")
                        time.sleep(30)
                    else:
                        init_Finish = True
            except SyntaxError as e2:
                print("语法错误")
                self.m_content.AppendText("再次重新进行连接" + "\r\n")

            except StopIteration as e3:
                print("发生异常")
                self.m_content.AppendText("再次重新进行连接" + "\r\n")


